<template>
    <div class="date-container">
        <!-- 当前时间显示区域 -->
        <n-card title="当前时间" class="time-card">
            <n-space vertical>
                <n-space>
                    <span class="label">时间字符串:</span>
                    <span>{{ currentDateTime }}</span>
                </n-space>
                <n-space>
                    <span class="label">毫秒时间戳:</span>
                    <span>{{ currentTimestamp }}</span>
                    <n-button text type="primary" size="tiny" @click="copyToClipboard(currentTimestamp)">
                        复制
                    </n-button>
                </n-space>
                <n-space>
                    <span class="label">秒时间戳:</span>
                    <span>{{ Math.floor(currentTimestamp / 1000) }}</span>
                    <n-button text type="primary" size="tiny"
                        @click="copyToClipboard(Math.floor(currentTimestamp / 1000))">
                        复制
                    </n-button>
                </n-space>
            </n-space>
        </n-card>

        <!-- 转换功能区域 -->
        <div class="convert-container">
            <!-- 时间转换区域 -->
            <n-card title="时间字符串转时间戳" class="convert-card">
                <n-space vertical>
                    <n-input v-model:value="inputDateTime" type="text"
                        placeholder="请输入时间字符串 (如: 2024-03-21 14:30:00)" />
                    <n-space>
                        <n-button @click="convertTime" :disabled="!inputDateTime">
                            转换
                        </n-button>
                        <n-button @click="clearInput">
                            清空
                        </n-button>
                    </n-space>
                    <template v-if="convertedTime.timestamp">
                        <n-space>
                            <span class="label">毫秒时间戳:</span>
                            <span>{{ convertedTime.timestamp }}</span>
                            <n-button text type="primary" size="tiny" @click="copyToClipboard(convertedTime.timestamp)">
                                复制
                            </n-button>
                        </n-space>
                        <n-space>
                            <span class="label">秒时间戳:</span>
                            <span>{{ Math.floor(convertedTime.timestamp / 1000) }}</span>
                            <n-button text type="primary" size="tiny"
                                @click="copyToClipboard(Math.floor(convertedTime.timestamp / 1000))">
                                复制
                            </n-button>
                        </n-space>
                    </template>
                </n-space>
            </n-card>

            <!-- 时间戳转时间字符串 -->
            <n-card title="时间戳转时间字符串" class="convert-card">
                <n-space vertical>
                    <n-radio-group v-model:value="timestampType">
                        <n-space>
                            <n-radio value="millisecond">毫秒时间戳</n-radio>
                            <n-radio value="second">秒时间戳</n-radio>
                        </n-space>
                    </n-radio-group>
                    <n-input v-model:value="inputTimestamp" type="text"
                        :placeholder="timestampType === 'millisecond' ? '请输入毫秒时间戳' : '请输入秒时间戳'" />
                    <n-space>
                        <n-button @click="convertTimestamp" :disabled="!inputTimestamp">
                            转换
                        </n-button>
                        <n-button @click="clearTimestampInput">
                            清空
                        </n-button>
                    </n-space>
                    <template v-if="convertedDateTime">
                        <n-space>
                            <span class="label">时间字符串:</span>
                            <span>{{ convertedDateTime }}</span>
                            <n-button text type="primary" size="tiny" @click="copyToClipboard(convertedDateTime)">
                                复制
                            </n-button>
                        </n-space>
                    </template>
                </n-space>
            </n-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 当前时间相关
const currentDateTime = ref('')
const currentTimestamp = ref(0)

// 时间转换相关
const inputDateTime = ref('')
const convertedTime = ref({
    timestamp: 0
})

// 更新当前时间的定时器
let timer: NodeJS.Timer | null = null

// 格式化日期时间
function formatDateTime(date: Date): string {
    const pad = (n: number) => n.toString().padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

// 更新当前时间
function updateCurrentTime() {
    const now = new Date()
    currentDateTime.value = formatDateTime(now)
    currentTimestamp.value = now.getTime()
}

// 转换输入的时间
function convertTime() {
    try {
        const timestamp = new Date(inputDateTime.value).getTime()
        if (isNaN(timestamp)) {
            throw new Error('Invalid date')
        }
        convertedTime.value.timestamp = timestamp
    } catch (error) {
        window.$message.error('无效的时间格式')
    }
}

// 清空输入
function clearInput() {
    inputDateTime.value = ''
    convertedTime.value.timestamp = 0
}

// 复制到剪贴板
async function copyToClipboard(text: number | string) {
    try {
        await navigator.clipboard.writeText(text.toString())
        window.$message.success('复制成功')
    } catch (err) {
        window.$message.error('复制失败')
    }
}

// 时间戳转换相关
const timestampType = ref<'millisecond' | 'second'>('millisecond')
const inputTimestamp = ref('')
const convertedDateTime = ref('')

// 转换时间戳为时间字符串
function convertTimestamp() {
    try {
        let timestamp = parseInt(inputTimestamp.value)
        if (isNaN(timestamp)) {
            throw new Error('Invalid timestamp')
        }

        // 如果是秒时间戳，转换为毫秒
        if (timestampType.value === 'second') {
            timestamp *= 1000
        }

        const date = new Date(timestamp)
        if (date.toString() === 'Invalid Date') {
            throw new Error('Invalid timestamp')
        }

        convertedDateTime.value = formatDateTime(date)
    } catch (error) {
        window.$message.error('无效的时间戳格式')
    }
}

// 清空时间戳输入
function clearTimestampInput() {
    inputTimestamp.value = ''
    convertedDateTime.value = ''
}

onMounted(() => {
    updateCurrentTime()
    timer = setInterval(updateCurrentTime, 1000)
})

onUnmounted(() => {
    if (timer) {
        clearInterval(timer)
    }
})
</script>

<style scoped>
.date-container {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.convert-container {
    display: flex;
    gap: 20px;
}

.time-card {
    max-width: 600px;
}

.convert-card {
    flex: 1;
    min-width: 0;
    /* 防止flex子项溢出 */
}

.label {
    font-weight: bold;
    min-width: 100px;
}
</style>